﻿using System.Collections.Generic;
using System.Linq;

namespace PLC
{
    /// <summary>
    /// 泛型定长数据队列
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class DataQueue<T>
    {
        public DataQueue(int length)
        {
            dataQueue = new Queue<T>(length);
            this.length = length;
            queueLocker = new object();
        }

        /// <summary>
        /// 队列长度
        /// </summary>
        private int length;
        /// <summary>
        /// 泛型队列
        /// </summary>
        private Queue<T> dataQueue;
        private readonly object queueLocker;

        /// <summary>
        /// 向列尾插入元素
        /// 并移去列首超出数量的元素
        /// </summary>
        /// <param name="value"></param>
        public void Enqueue(T value)
        {
            lock (queueLocker)
            {
                dataQueue.Enqueue(value);
                if (dataQueue.Count > length)
                    dataQueue.Dequeue();
            }
        }

        /// <summary>
        /// 是否整个队列的数据都相同、
        /// </summary>
        public bool IsSame
        {
            get
            {
                lock (queueLocker)
                {
                    if (dataQueue.Count < length)
                        return false;

                    return dataQueue.Distinct().Count() == 1;

                }
            }
        }
    }
}
